<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2022/02/20
 * Time: 5:44 PM
 */

namespace addons\unidrink\controller;

use addons\unidrink\model\ScoreOrder;
use addons\unidrink\model\ScoreProduct;
use addons\unidrink\extend\Ali;
use app\admin\model\unidrink\Bill;
use app\common\model\ScoreLog;
use think\Db;
use think\Exception;

/**
 * 积分商城
 */
class ScoreShop extends Base
{

    protected $noNeedLogin = ['index', 'detail'];

    /**
     * @ApiTitle    (产品列表)
     * @ApiSummary  (产品列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=platform, type=string, required=false, description="平台")
     * @ApiHeaders  (name=token, type=string, required=true, description="登录token")
     * @ApiParams   (name="page", type="integer", required=false, description="页面")
     * @ApiParams   (name="pagesize", type="integer", required=false, description="页数")
     * @ApiReturn   ({"code":1,"msg":"","data":[]})
     *
     * @ApiReturnParams  (name="id", type="integer", description="积分记录id")
     * @ApiReturnParams  (name="image", type="string", description="图片")
     * @ApiReturnParams  (name="score", type="integer", description="获得积分")
     * @ApiReturnParams  (name="stock", type="integer", description="库存")
     * @ApiReturnParams  (name="sales", type="integer", description="销售量")
     * @ApiReturnParams  (name="title", type="string", description="产品名称")
     */
    public function index()
    {
        $page = $this->request->request('page', 1);
        $pagesize = $this->request->request('pagesize', 16);

        $list = (new \addons\unidrink\model\ScoreProduct())
            ->where(['switch' => 1])
            ->field('id,image,score,stock,sales,title')
            ->order('weigh', 'desc')
            ->page($page, $pagesize)
            ->select();

        $this->success('', $list);

    }


    /**
     * @ApiTitle    (产品详情)
     * @ApiSummary  (产品详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=platform, type=string, required=false, description="平台")
     * @ApiHeaders  (name=token, type=string, required=true, description="登录token")
     * @ApiParams   (name="id", type="integer", required=true, description="产品id")
     * @ApiReturn   ({"code":1,"msg":"","data":[]})
     *
     * @ApiReturnParams  (name="id", type="integer", description="积分记录id")
     * @ApiReturnParams  (name="image", type="string", description="图片")
     * @ApiReturnParams  (name="score", type="integer", description="获得积分")
     * @ApiReturnParams  (name="stock", type="integer", description="库存")
     * @ApiReturnParams  (name="sales", type="integer", description="销售量")
     * @ApiReturnParams  (name="title", type="string", description="产品名称")
     * @ApiReturnParams  (name="images", type="array", description="图片轮播图")
     * @ApiReturnParams  (name="desc", type="string", description="详情")
     */
    public function detail()
    {
        $id = $this->request->request('id');
        $data = (new \addons\unidrink\model\ScoreProduct())->find($id);
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (积分兑换商品)
     * @ApiSummary  (积分兑换商品)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=platform, type=string, required=false, description="平台")
     * @ApiHeaders  (name=token, type=string, required=true, description="登录token")
     * @ApiParams   (name="id", type="integer", required=true, description="产品id")
     * @ApiParams   (name="address_id", type="integer", required=true, description="地址id")
     * @ApiParams   (name="num", type="integer", required=true, description="产品数量")
     * @ApiReturn   ({"code":1,"msg":"","data":[]})
     */
    public function exchange()
    {
        $id = $this->request->request('id');
        $addressId = $this->request->request('address_id');
        $num = $this->request->request('num');
        if ($num < 0) {
            $this->error('数量必须大于1');
        }
        $address = (new \addons\unidrink\model\Address)->find([
            'id' => $addressId,
            'user_id' => $this->auth->id,
        ]);
        if (!$address) {
            $this->error('收货地址不存在');
        }
        Db::startTrans();
        try {
            $product = (new ScoreProduct)->where(['id' => $id])->lock(true)->find();
            if (!$product) {
                $this->error('商品不存在');
            }
            $totalScore = $product->score * $num;
            if ($this->auth->score < $totalScore) {
                $this->error('积分不足，无法兑换');
            }
            if ($product->stock < $num) {
                $this->error('库存不足');
            }
            $product->setDec('stock', $num);

            ScoreOrder::create([
                'user_id' => $this->auth->id,
                'product_id' => $product->id,
                'number' => $num,
                'score' => $product->score,
                'total_score' => $product->score * $num,
                'ip' => $_SERVER['REMOTE_ADDR'],
                'status' => 1,
                'have_paid' => time(),
                'customer_name' => $address['name'],
                'customer_address' => $address['address'] . ' ' . $address['door_number'],
                'customer_phone' => $address['mobile'],
            ]);

            $before = $this->auth->score;
            $after = $before - $totalScore;
            $level = \app\common\model\User::nextlevel($after);
            //更新会员信息
            $this->auth->getUser()->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create([
                'user_id' => $this->auth->id,
                'score' => $totalScore,
                'before' => $before,
                'after' => $after,
                'memo' => '积分购物'
            ]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('兑换成功', 1);
    }

    /**
     * @ApiTitle    (兑换订单列表)
     * @ApiSummary  (兑换订单列表)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=cookie, type=string, required=false, description="用户会话的cookie")
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="page", type=integer, required=true, description="页面")
     * @ApiParams   (name="pagesize", type=integer, required=true, description="页数")
     *
     * @ApiReturn   ({"code":1,"msg":"","data":[]})
     *
     * @ApiReturnParams  (name="createtime", type="string", description="下单时间")
     * @ApiReturnParams  (name="customer_address", type="string", description="收货人地址")
     * @ApiReturnParams  (name="customer_name", type="string", description="收货人名称")
     * @ApiReturnParams  (name="customer_phone", type="string", description="收货人电话")
     * @ApiReturnParams  (name="express_company", type="string", description="快递公司")
     * @ApiReturnParams  (name="express_number", type="string", description="快递单号")
     * @ApiReturnParams  (name="order_status_text", type="string", description="订单状态")
     * @ApiReturnParams  (name="have_delivered", type="integer", description="发货时间")
     * @ApiReturnParams  (name="have_delivered", type="integer", description="发货时间戳")
     * @ApiReturnParams  (name="have_paid", type="integer", description="兑换时间戳")
     * @ApiReturnParams  (name="have_received", type="integer", description="收货时间戳")
     * @ApiReturnParams  (name="number", type="integer", description="数量")
     * @ApiReturnParams  (name="score", type="integer", description="单个积分")
     * @ApiReturnParams  (name="total_score", type="integer", description="总积分")
     *
     * @ApiReturnParams  (name="product", type="array", description="商品数组")
     * @ApiReturnParams  (name="product.id", type="integer", description="订单的商品id")
     * @ApiReturnParams  (name="product.title", type="string", description="商品标题")
     *
     */
    public function order()
    {
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        try {

            $model = (new ScoreOrder());
            $data = $model
                ->with([
                    'product' => function ($query) {
                        $query->field('title,id');
                    }
                ])
                ->order('id', 'desc')
                ->page($page, $pagesize)
                ->select();

            foreach ($data as &$item) {
                $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                // 订单状态
                $item['order_status_text'] = $model->orderStatusText($item);
            }

            $this->success('', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @ApiTitle    (订单详情)
     * @ApiSummary  (订单详情)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=cookie, type=string, required=false, description="用户会话的cookie")
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="id", type=integer, required=true, description="订单id")
     *
     * @ApiReturn   ({"code":1,"msg":"","data":1})
     *
     * @ApiReturnParams  (name="createtime", type="string", description="下单时间")
     * @ApiReturnParams  (name="customer_address", type="string", description="收货人地址")
     * @ApiReturnParams  (name="customer_name", type="string", description="收货人名称")
     * @ApiReturnParams  (name="customer_phone", type="string", description="收货人电话")
     * @ApiReturnParams  (name="express", type="string", description="快递公司拼音")
     * @ApiReturnParams  (name="express_company", type="string", description="快递公司")
     * @ApiReturnParams  (name="express_number", type="string", description="快递单号")
     * @ApiReturnParams  (name="order_status_text", type="string", description="订单状态")
     * @ApiReturnParams  (name="have_delivered", type="integer", description="发货时间")
     * @ApiReturnParams  (name="have_delivered", type="integer", description="发货时间戳")
     * @ApiReturnParams  (name="have_paid", type="integer", description="兑换时间戳")
     * @ApiReturnParams  (name="have_received", type="integer", description="收货时间戳")
     * @ApiReturnParams  (name="number", type="integer", description="数量")
     * @ApiReturnParams  (name="score", type="integer", description="单个积分")
     * @ApiReturnParams  (name="total_score", type="integer", description="总积分")
     *
     * @ApiReturnParams  (name="product", type="array", description="商品数组")
     * @ApiReturnParams  (name="product.id", type="integer", description="订单的商品id")
     * @ApiReturnParams  (name="product.title", type="string", description="商品标题")
     * @ApiReturnParams  (name="product.image", type="string", description="商品图片")
     *
     */
    public function orderDetail()
    {
        $id = $this->request->request('id');
        try {
            $data = (new ScoreOrder())->with('product')
                ->where([
                    'id' => $id,
                    'user_id' => $this->auth->id,
                ])
                ->find()->toArray();
            if (empty($data)) {
                $this->error('订单不存在');
            }
            $data['express'] = $data['express_number'];

            $data['order_status_text'] = (new ScoreOrder())->orderStatusText($data);
            $data['createtime'] = date('Y-m-d H:i:s', $data['createtime']);
            $this->success('', $data);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * @ApiTitle    (确认收到)
     * @ApiSummary  (确认收到)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=cookie, type=string, required=false, description="用户会话的cookie")
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="id", type=integer, required=true, description="订单id")
     *
     * @ApiReturn   ({"code":1,"msg":"","data":1})
     *
     */
    public function receive()
    {
        $order_id = $this->request->request('id');
        try {
            $order = ScoreOrder::update(
                [
                    'have_received' => time()
                ],
                [
                    'id' => $order_id,
                    'user_id' => $this->auth->id
                ]
            );
            if ($order) {
                $this->success('成功', time());
            } else {
                $this->error('失败');
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }

    /**
     * @ApiTitle    (快递查询)
     * @ApiSummary  (快递查询)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=cookie, type=string, required=false, description="用户会话的cookie")
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="express", type="string",required=true, description="寄货物流公司")
     * @ApiParams   (name="expresssn", type="string",required=true, description="寄货物流单号")
     * @ApiReturn   ({"code":1,"msg":"","data":1})
     *
     */
    public function express()
    {
        $params = $this->request->post();

        try {
            $express = new Ali();
            $data = $express->express($params['expresssn']);
            if ($data['code'] != 0) {
                throw new Exception($data['reason'] ?? '');
            }

            // 做预处理 数据转换
            $list = $data['result']['list'] ?? [];
            foreach ($list as &$value) {
                $value = [
                    'time' => $value['node_time'],
                    'step' => $value['node_desc'],
                ];
            }

        } catch (Exception $e) {
            $this->success('', [
                'message' => [],
                'company' => '快递单号',
            ]);
        }
        $this->success('', [
            'message' => $list ?? [],
            'company' => $data['result']['ExpressName'] ?? '快递单号'
        ]);
    }
}